//
//  VideoReportViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/5.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ReportViewController.h"
#import "VideoReportChoiceCell.h"
#import "VideoOtherContentCell.h"
#import "VideoDescContentCell.h"

#import "ReportArgModel.h"
@interface ReportViewController ()<UITableViewDelegate,UITableViewDataSource,VideoReportChoiceCellDelegate,VideoOtherContentCellDelegate,VideoDescContentCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *footerView;
@property (nonatomic,strong)UIButton *footerBtn;

@property (nonatomic,copy)NSArray *titleArray;

@property (nonatomic,strong)NSMutableArray *selectedArr;

@property (nonatomic,strong)ReportArgModel *argModel;

@property (nonatomic,strong)CAGradientLayer *confirmBtnGradientLayer;
@property (nonatomic,assign)XHReportType type;
@property (nonatomic,copy)NSString *reportId;

@end

@implementation ReportViewController

- (NSMutableArray *)selectedArr{
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}
- (ReportArgModel *)argModel{
    if (!_argModel) {
        _argModel = [[ReportArgModel alloc]init];
    }
    return _argModel;
}

- (CAGradientLayer *)confirmBtnGradientLayer{
    if (!_confirmBtnGradientLayer) {
        _confirmBtnGradientLayer =  [CAGradientLayer layer];
        _confirmBtnGradientLayer.frame = self.footerBtn.bounds;
        _confirmBtnGradientLayer.endPoint = CGPointMake(0, 0);
        _confirmBtnGradientLayer.startPoint  = CGPointMake(1.0, 0);
        _confirmBtnGradientLayer.colors = @[(id)RGBA(119, 153, 255, 1).CGColor,(id)RGBA(86, 128, 250, 1).CGColor];
    }
    return _confirmBtnGradientLayer;
}

- (instancetype)initWithReportType:(XHReportType)type reportId:(NSString *)reportId{
    if (self = [super init]) {
        self.reportId = reportId;
        self.type = type;
        [self setUI];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleArray = @[@"违法违规",@"暴恐",@"血腥暴力",@"色情低俗",@"垃圾信息",@"未成年人有害"];
    
    [self setUI];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    
    self.navigationItem.title = @"投诉";
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    self.tableView.backgroundColor = RGBA(248, 248, 248, 1);
    
    self.view.backgroundColor = RGBA(248, 248, 248, 1);
    
    [self setFooterView];
    
    self.tableView.tableFooterView = self.footerView;
    
}

- (void)setFooterView{
    
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 100)];
    self.footerBtn = [[UIButton alloc]initWithFrame:CGRectMake(16, 21, kScreenW - 32, 44)];
    self.footerBtn.layer.cornerRadius = 22;
    self.footerBtn.layer.masksToBounds = YES;
    [self.footerBtn setTitle:@"提交" forState:UIControlStateNormal];
    self.footerBtn.backgroundColor = RGBA(234, 234, 245, 1);
    [self.footerView addSubview:self.footerBtn];
    [self.footerBtn addTarget:self action:@selector(footerMethod) forControlEvents:UIControlEventTouchUpInside];
    
    self.footerBtn.userInteractionEnabled = NO;
}

#pragma mark - method

- (void)back{
    if (self.done) {
        self.done();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)footerMethod{
    
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    param[@"userId"] = [RPAppManager getCustomerId];
    
    NSString *contact = @"";
    if (self.argModel.qq.length != 0) {
        contact = [contact stringByAppendingFormat:@"%@/",self.argModel.qq];
    }else{
        contact = [contact stringByAppendingFormat:@"0/"];
    }
    if (self.argModel.phone.length != 0) {
        contact = [contact stringByAppendingFormat:@"%@/",self.argModel.phone];
    }else{
        contact = [contact stringByAppendingString:@"0/"];
    }
    if (self.argModel.mail.length != 0) {
        contact = [contact stringByAppendingFormat:@"%@",self.argModel.mail];
    }else{
        contact = [contact stringByAppendingString:@"0"];
    }
    param[@"contact"] = contact;
    
    NSString *content = @"";
    NSMutableArray *strArr = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(NSNumber  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [strArr addObject:self.titleArray[obj.intValue]];
    }];
    
    NSString *str = [strArr componentsJoinedByString:@"/"];
    
    content = [content stringByAppendingFormat:@"%@:%@:%@",self.reportId,str,self.argModel.desc];
    
    param[@"content"] = content;
    
    param[@"md5"] = [RPAppManager md5StrWithApi:AddFeedback];
    
    [SVProgressHUD show];
    
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddFeedback) parames:param success:^(id responseObj) {
            NSString *att = @"我们会尽快处理您的问题！";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"反馈成功" message:att preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alertController dismissViewControllerAnimated:YES completion:nil];
                [self.navigationController popViewControllerAnimated:YES];
                if (self.type == XHREPORTVIDEO) {
                    if (self.done) {
                        self.done();
                    }
                }
            }];
            NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:att];
            [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:RGBA(102, 102, 102, 1) range:NSMakeRange(0, att.length)];
            [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, att.length)];
            [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
            [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
            //往alertViewController上添加alertAction
            [alertController addAction:confirmAction];
            [self presentViewController:alertController animated:YES completion:nil];
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
    

}
#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.titleArray.count;
    }
    if (section == 2) {
        return 3;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        VideoReportChoiceCell *cell = [VideoReportChoiceCell cellWithTableView:tableView];
        [cell setContent:self.titleArray[indexPath.row] index:indexPath.row isSelected:[self.selectedArr containsObject:@(indexPath.row)]];
        [cell isHideLine:self.titleArray.count - 1 == indexPath.row];
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section == 1) {
        VideoDescContentCell *cell = [VideoDescContentCell cellWithTableView:tableView];
        [cell setDescContent:self.argModel.desc];
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section == 2) {
        VideoOtherContentCell *cell = [VideoOtherContentCell cellWithTableView:tableView];
        if (indexPath.row == 0) {
            [cell setOtherContent:self.argModel.phone type:XHOTHERRERORTPHONE isMine:NO];
        }else if (indexPath.row == 1){
            [cell setOtherContent:self.argModel.qq type:XHOTHERRERORTQQ isMine:NO];
        }else if (indexPath.row == 2){
            [cell setOtherContent:self.argModel.mail type:XHOTHERRERORTMAIL isMine:NO];
        }
        cell.delegate = self;
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"请选择您遇到的具体问题（必选）";
    }
    if (section == 1) {
        return @"问题描述（选填）";
    }
    if (section == 2) {
        return @"联系方式（选填）";
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return 170.0f;
    }
    if (indexPath.section == 2) {
        return 60.0f;
    }
    return 50.0;
}
#pragma mark - VideoReportChoiceCellDelegate
- (void)didSelectedAtIndex:(NSInteger)index{
    if ([self.selectedArr containsObject:@(index)]) {
        [self.selectedArr removeObject:@(index)];
    }else{
        [self.selectedArr addObject:@(index)];
    }
    
    if (self.selectedArr.count > 0) {
        if (![self.footerBtn.layer.sublayers containsObject:self.confirmBtnGradientLayer]) {
            [self.footerBtn.layer insertSublayer:self.confirmBtnGradientLayer atIndex:0];
        }
    }else{
        [self.confirmBtnGradientLayer removeFromSuperlayer];
    }
    self.footerBtn.userInteractionEnabled = self.selectedArr.count > 0;
}
#pragma mark - VideoOtherContentCellDelegate
- (void)videoOtherContentEndEditing:(NSString *)content type:(XHOtherReportType)type{
    if (type == XHOTHERRERORTPHONE) {
        self.argModel.phone = content;
    }
    if (type == XHOTHERRERORTMAIL) {
        self.argModel.mail = content;
    }
    if (type == XHOTHERRERORTQQ) {
        self.argModel.qq = content;
    }
}
#pragma mark - VideoDescContentCellDelegate
- (void)videoDescContentEndEditing:(NSString *)content{
    self.argModel.desc = content;
}
- (void)videoDescDidChange:(NSString *)content{
   
    
    if (self.selectedArr.count > 0) {
        if (![self.footerBtn.layer.sublayers containsObject:self.confirmBtnGradientLayer]) {
            [self.footerBtn.layer insertSublayer:self.confirmBtnGradientLayer atIndex:0];
        }
    }else{
        [self.confirmBtnGradientLayer removeFromSuperlayer];
    }
    self.footerBtn.userInteractionEnabled = self.selectedArr.count > 0;
}

@end
